package ray.wx.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import ray.wx.util.MysqlUtil;

/**
 * Servlet implementation class DataLoadServlet
 */
@WebServlet("/DataLoadServlet")
public class DataLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DataLoadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    public static int StringToInt(String str, int def) {
        int intRet = def;
        try {
            if (str == null || str.trim().equals(""))
                str = def + "";
            intRet = Integer.parseInt(str);
        }
        catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return intRet;
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
        String strPage = request.getParameter("page");  
        String strNum = request.getParameter("num");
        
        MysqlUtil mysql = new MysqlUtil(MysqlUtil.dbUrl, MysqlUtil.dbUser, MysqlUtil.dbPass);
        try {
			mysql.connect();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    return;
			//throw new ServletException("Database init failed!");
		}
        
        int page = StringToInt(strPage, 0);
        int num = StringToInt(strNum, 0);
        int start_index = ((page - 1) * num) + 1;

    	String sql = "select count(*) from key_reply_msg;";
    	int record_cnt = mysql.get_record_count(sql);
        
        JSONArray jsonArray = new JSONArray();
        
        int total_page = record_cnt % num;
        total_page = (total_page == 0)?(record_cnt/num):((record_cnt/num)+1);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("total_page", new Integer(total_page));
        jsonArray.add(jsonObject1);    	
    	
        if (page == -1){
        	record_cnt = (record_cnt == 0)?record_cnt:(record_cnt-1);
        	start_index = (record_cnt / num) * num + 1;
        }
        
        int count = 1;
        int j = 0;
        
        ResultSet result;
        sql = "select key_id, input_key, reply from key_reply_msg;";
		try {
			result = mysql.get_record_value(sql);
			while (result.next() && j < num){
				if (count >= start_index){
					String strID = result.getString(1);
					String strKey1 = result.getString(2);
					//strKey1 = strKey1.replace(" ", "%20");
					String strKey = URLEncoder.encode(strKey1,"utf-8");
					String strReply1 = result.getString(3);
					//strReply1 = strReply1.replace(" ", "%20");
					String strReply = URLEncoder.encode(strReply1,"utf-8");
					j++;
					
					
					JSONObject jsonObject = new JSONObject(); 
					jsonObject.put("index", new Integer(count));
					jsonObject.put("key", strKey);
					jsonObject.put("reply", strReply);
					jsonObject.put("id", strID);
					
					jsonArray.add(jsonObject);
					
					//KeyReplyTables record = new KeyReplyTables(count, strKey, strReply);
					//tablesList.add(record);
				}
				
                count++;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    return;
		}
		
		PrintWriter out = response.getWriter();  
        out.print(jsonArray.toString()); 
        out.close();
        out = null;
        return;
        
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
